local extension = Package("fengqi_forest")
extension.extensionName = "aaa_fengqi"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["fengqi_forest"] = "林",
}


local caopi = General(extension, "efengqi__caopi", "wei", 3)

local fangzhu = fk.CreateTriggerSkill{
  name = "efengqi__fangzhu",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player), Util.IdMapper)
    , 1, 1, "#efengqi__fangzhu-choose:::"..player:getLostHp(), self.name, true)
    if #to > 0 then
      self.cost_data = {tos = to}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local to = player.room:getPlayerById(self.cost_data.tos[1])
    to:turnOver()
    if not to.dead and player:getLostHp() > 0 then
      to:drawCards(player:getLostHp(), self.name)
    end
  end,
}
caopi:addSkill(fangzhu)

local xingshang = fk.CreateTriggerSkill{
  name = "efengqi__xingshang",
  anim_type = "defensive",
  events = {fk.Death},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and not (target:isNude() and not player:isWounded())
  end,
  on_cost = function(self, event, target, player, data)
    local choices = {"Cancel"}
    if player:isWounded() then table.insert(choices, 1, "recover") end
    if not target:isNude() then table.insert(choices, 1, "efengqi__xingshang_obtain::" .. target.id) end
    local choice = player.room:askForChoice(player, choices, self.name)
    if choice ~= "Cancel" then
      self.cost_data = {choice = choice, tos = {target.id}}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if self.cost_data.choice == "recover" then
      room:recover({
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      })
    else
      room:obtainCard(player, target:getCardIds("he"), false, fk.ReasonPrey, player.id, self.name)
    end
  end,
}
caopi:addSkill(xingshang)

local songwei = fk.CreateTriggerSkill{
  name = "efengqi__songwei$",
  events = {fk.FinishJudge},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and data.card.color == Card.Black
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(target, self.name, nil, "#efengqi__songwei-invoke:"..player.id)
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
    if not target.dead and not player.dead and target.kingdom == "wei" and
    player.room:askForSkillInvoke(player, self.name, nil, "#efengqi__songwei-invoke:"..target.id) then
      target:drawCards(1, self.name)
    end
  end,
}
caopi:addSkill(songwei)

Fk:loadTranslationTable{
  ["efengqi__caopi"] = "曹丕",
  ["#efengqi__caopi"] = "魏文帝",
  ["designer:efengqi__caopi"] = "",
  ["illustrator:efengqi__caopi"] = "蛋勒个蛋蛋蛋蛋蛋",

  ["efengqi__fangzhu"] = "放逐",
  [":efengqi__fangzhu"] = "当你受到伤害后，你可以令一名其他角色翻面，然后其摸X张牌（X为你已损失的体力值）。",
  ["#efengqi__fangzhu-choose"] = "放逐：你可以令一名其他角色翻面，然后其摸%arg张牌",

  ["efengqi__xingshang"] = "行殇",
  [":efengqi__xingshang"] = "当其他角色死亡时，你可以选择一项：1.获得其所有牌；2.回复1点体力。",
  ["efengqi__xingshang_obtain"] = "获得%dest的所有牌",

  ["efengqi__songwei"] = "颂威",
  [":efengqi__songwei"] = "其他角色的黑色判定牌生效后，其可以令你摸一张牌，然后若其为魏势力角色，你可以令其摸一张牌。",
  ["#efengqi__songwei-invoke"] = "颂威：你可以令 %src 摸一张牌",

  ["$efengqi__xingshang1"] = "我的是我的，你的还是我的。",
  ["$efengqi__xingshang2"] = "来，管杀还管埋！",
  ["$efengqi__fangzhu1"] = "死罪可免，活罪难赦！",
  ["$efengqi__fangzhu2"] = "给我翻过来！",
  ["$efengqi__songwei1"] = "千秋万载，一统江山！",
  ["$efengqi__songwei2"] = "仙福永享，寿与天齐！",
  ["~efengqi__caopi"] = "子建，子建……",
}

local xuhuang = General(extension, "efengqi__xuhuang", "wei", 4)
local jieliang = fk.CreateTriggerSkill{
  name = "efengqi__jieliang",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target ~= player and player:hasSkill(self) and target.phase == Player.Draw and not player:isNude() and
    player:usedSkillTimes(self.name, Player.HistoryRound) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local card = player.room:askForDiscard(player, 1, 1, true, self.name, true, ".|.|spade,club|.|.|^trick",
      "#efengqi__jieliang-invoke::"..target.id, true)
    if #card > 0 then
      self.cost_data = {tos = {target.id}, cards = card}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data.cards, self.name, player, player)
    if player.dead then return end
    local cards = room:getNCards(2)
    while not player.dead and #cards > 0 do
      local use = U.askForUseRealCard(room, player, cards, nil, self.name, "#efengqi__jieliang-use", {
        bypass_times = true,
        extraUse = true,
        expand_pile = cards,
      }, false, true)
      if use then
        table.removeOne(cards, use.card.id)
        if not target.dead then
          room:addPlayerMark(target, "efengqi__jieliang-phase", 1)
        end
      else
        break
      end
    end
  end,

  refresh_events = {fk.DrawNCards},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark("efengqi__jieliang-phase") > 0
  end,
  on_refresh = function (self, event, target, player, data)
    data.n = data.n - player:getMark("efengqi__jieliang-phase")
    player.room:setPlayerMark(player, "efengqi__jieliang-phase", 0)
  end,
}
xuhuang:addSkill(jieliang)
Fk:loadTranslationTable{
  ["efengqi__xuhuang"] = "徐晃",
  ["#efengqi__xuhuang"] = "周亚夫之风",
  ["designer:efengqi__xuhuang"] = "屑",
  ["illustrator:efengqi__xuhuang"] = "鬼画府",

  ["efengqi__jieliang"] = "截粮",
  [":efengqi__jieliang"] = "每轮限一次，其他角色摸牌阶段开始时，你可以弃置一张黑色非锦囊牌，观看并使用牌堆顶两张牌，每使用一张牌，此阶段少摸一张牌。",
  ["#efengqi__jieliang-invoke"] = "截粮：你可以弃置一张黑色非锦囊牌，观看并使用牌堆顶两张牌，每使用一张令 %dest 少摸一张牌",
  ["#efengqi__jieliang-use"] = "截粮：你可以使用其中一张牌",

  ["$efengqi__jieliang1"] = "截其源，断其粮，贼可擒也。",
  ["$efengqi__jieliang2"] = "人是铁，饭是钢。",
  ["~efengqi__xuhuang"] = "一顿不吃饿得慌。",
}

local dongzhuo = General(extension, "efengqi__dongzhuo", "han", 8)

local chengxiong = fk.CreateViewAsSkill{
  name = "efengqi__chengxiong",
  anim_type = "offensive",
  pattern = "analeptic",
  prompt = "#efengqi__chengxiong",
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).suit == Card.Spade
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return nil end
    local c = Fk:cloneCard("analeptic")
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
}
local efengqi__chengxiong_targetmod = fk.CreateTargetModSkill{
  name = "#efengqi__chengxiong_targetmod",
  bypass_times = function(self, player, skill, scope, card, to)
    -- 太愚蠢了，酒的canUse用无色牌判断，无法令指定花色的牌无次数限制
    if card and table.contains(card.skillNames, chengxiong.name) then return true end
    if card and card.suit == Card.Spade then
      return player:hasSkill(chengxiong) or (to and to:hasSkill(chengxiong))
    end
  end,
  bypass_distances = function (self, player, skill, card, to)
    if card and card.suit == Card.Spade then
      return player:hasSkill(chengxiong) or (to and to:hasSkill(chengxiong))
    end
  end,
}
chengxiong:addRelatedSkill(efengqi__chengxiong_targetmod)
dongzhuo:addSkill(chengxiong)

local benghuai = fk.CreateTriggerSkill{
  name = "efengqi__benghuai",
  anim_type = "negative",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish and
      table.find(player.room.alive_players, function(p) return p.hp < player.hp end)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(player, {"loseMaxHp", "loseHp"}, self.name)
    if choice == "loseMaxHp" then
      room:changeMaxHp(player, -1)
    else
      room:loseHp(player, 1, self.name)
    end
  end,
}
dongzhuo:addSkill(benghuai)

local efengqi__dufu = fk.CreateTriggerSkill{
  name = "efengqi__dufu$",
  anim_type = "offensive",
  events = {fk.Damage, fk.BuryVictim},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.BuryVictim then
        return data.damage and data.damage.from == player and target.kingdom ~= "han" and target.rest == 0
        and not (data.extra_data and data.extra_data.skip_reward_punish)
      elseif target and target.kingdom == "han" and not target.dead then
        local damageEvent = player.room.logic:getActualDamageEvents(1, function(e) return e.data[1].from == target end)[1]
        return damageEvent and damageEvent.data[1] == data
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.BuryVictim then return true end
    return player.room:askForSkillInvoke(target, self.name, data, "#efengqi__dufu-draw:"..player.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.BuryVictim then
      -- 跳过奖惩并摸三张……
      data.extra_data = data.extra_data or {}
      data.extra_data.skip_reward_punish = true
      player:drawCards(3, self.name)
    else
      target:drawCards(1, self.name)
      if not player.dead then
        player:drawCards(1, self.name)
      end
    end
  end
}
dongzhuo:addSkill(efengqi__dufu)

Fk:loadTranslationTable{
  ["efengqi__dongzhuo"] = "董卓",
  ["#efengqi__dongzhuo"] = "",
  ["designer:efengqi__dongzhuo"] = "屑",
  ["illustrator:efengqi__dongzhuo"] = "错落宇宙",

  ["efengqi__chengxiong"] = "逞凶",
  [":efengqi__chengxiong"] = "你可以将一张♠牌当【酒】使用；使用者为你或目标含你的♠牌无视次数与距离。",
  ["#efengqi__chengxiong"] = "逞凶:你可以将一张♠牌当【酒】使用",

  ["efengqi__benghuai"] = "崩坏",
  [":efengqi__benghuai"] = "锁定技，结束阶段，若你不是体力值最小的角色，你选择：1.减1点体力上限；2.失去1点体力。",

  ["efengqi__dufu"] = "独夫",
  [":efengqi__dufu"] = "主公技，杀死非汉势力角色的奖惩改为摸三张牌；汉势力角色每回合首次造成伤害后，可以与你各摸一张牌。",
  ["#efengqi__dufu-draw"] = "独夫:你可以与 %src 各摸一张牌",

  ["$efengqi__chengxiong1"] = "呃……再来……一壶……",
  ["$efengqi__chengxiong2"] = "好酒！好酒！",
  ["$efengqi__benghuai1"] = "我是不是该减肥了？",
  ["$efengqi__benghuai2"] = "呃……",
  ["$efengqi__dufu1"] = "顺我者昌，逆我者亡！",
  ["$efengqi__dufu2"] = "哈哈哈哈！",
  ["~efengqi__dongzhuo"] = "汉室衰弱，非我一人之罪。",
}

local jiaxu = General(extension, "efengqi__jiaxu", "qun", 3)

local wansha = fk.CreateFilterSkill{
  name = "efengqi__wansha",
  mute = true,
  card_filter = function(self, card, player)
    local current = table.find(Fk:currentRoom().alive_players, function(p) return p.phase ~= Player.NotActive end)
    if player and current and current ~= player and current:hasSkill(self) and not player.dying then
      return card.trueName == "peach" or card.trueName == "nullification"
    end
  end,
  view_as = function(self, card)
    local c = Fk:cloneCard("slash", card.suit, card.number)
    c.skillName = self.name
    return c
  end,
}

local wansha_trigger = fk.CreateTriggerSkill{
  name = "#efengqi__wansha_trigger",
  refresh_events = {fk.EnterDying, fk.AfterDying, fk.EventLoseSkill},
  can_refresh = function (self, event, target, player, data)
    if event == fk.EventLoseSkill then return data == wansha and target == player end
    return player:hasSkill(wansha) and player.phase ~= Player.NotActive
  end,
  on_refresh = function (self, event, target, player, data)
    if event == fk.EnterDying then
      player:broadcastSkillInvoke(wansha.name)
      player.room:notifySkillInvoked(player, wansha.name, "offensive")
    end
    for _, p in ipairs(player.room.alive_players) do
      p:filterHandcards()
    end
  end,
}
wansha:addRelatedSkill(wansha_trigger)

jiaxu:addSkill(wansha)

local weimu = fk.CreateTriggerSkill{
  name = "efengqi__weimu",
  anim_type = "defensive",
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if player.phase == Player.NotActive then
        return not player:isKongcheng() and not player:hasDelayedTrick("lightning")
        and not table.contains(player.sealedSlots, Player.JudgeSlot)
      else
        return true
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if player.phase ~= Player.NotActive then return player.room:askForSkillInvoke(player, self.name, data, "#efengqi__weimu-draw") end
    local ids = table.filter(player:getCardIds("h"), function (id)
      if Fk:getCardById(id).type == Card.TypeTrick then
        local c = Fk:cloneCard("lightning")
        c.skillName = self.name
        c:addSubcard(id)
        return not player:prohibitUse(c) and player:canUse(c)
      end
    end)
    ids = player.room:askForCard(player, 1, 1, false, self.name, true, tostring(Exppattern{ id = ids }), "#efengqi__weimu-use")
    if #ids > 0 then
      self.cost_data = {cards = ids}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    if player.phase ~= Player.NotActive then
      player:drawCards(data.damage, self.name)
      return true
    end
    local c = Fk:cloneCard("lightning")
    c.skillName = self.name
    c:addSubcard(self.cost_data.cards[1])
    player.room:useCard{from = player.id, tos = {{player.id}}, card = c}
    return true
  end,
}
jiaxu:addSkill(weimu)

local luanwu = fk.CreateTriggerSkill{
  name = "efengqi__luanwu",
  anim_type = "offensive",
  frequency = Skill.Limited,
  events = {fk.RoundStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = room:getAlivePlayers()
    room:doIndicate(player.id, table.map(targets, Util.IdMapper))

    -- 应该封装一下
    local choices = {"efengqi__luanwu_poison", "efengqi__luanwu_turnover", "efengqi__luanwu_draw2"}
    local req = Request:new(targets, "AskForChoices")
    req.focus_text = self.name
    local req_data = {
      choices, choices, {2, 2}, false, self.name, "#efengqi__luanwu-choice", false
    }
    for _, p in ipairs(targets) do
      req:setData(p, req_data)
      req:setDefaultReply(p, table.random(choices, 2))
    end
    req:ask()
    local result = {}
    for _, p in ipairs(targets) do
      result[p.id] = req:getResult(p)
    end

    for _, p in ipairs(targets) do
      local ret = result[p.id]
      if not p.dead then
        if table.contains(ret, choices[1]) then
          room:setPlayerMark(p, "@@efengqi__luanwu_zhendu-round", 1)
          room:handleAddLoseSkills(p, "efengqi__zhendu")
          room.logic:getCurrentEvent():findParent(GameEvent.Round):addCleaner(function()
            room:handleAddLoseSkills(p, "-efengqi__zhendu")
          end)
        end
      end
      if not p.dead and table.contains(ret, choices[2]) then
        p:turnOver()
      end
      if not p.dead and table.contains(ret, choices[3]) then
        p:drawCards(2, self.name)
      end
    end
  end,
}
jiaxu:addSkill(luanwu)


local efengqi__zhendu = fk.CreateTriggerSkill{
  name = "efengqi__zhendu",
  mute = true,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target.phase == Player.Play and not player:isKongcheng() and not target.dead
  end,
  on_cost = function(self, event, target, player, data)
    local prompt = (target == player) and "#efengqi__zhendu-self" or "#efengqi__zhendu-invoke::"..target.id
    local card = player.room:askForDiscard(player, 1, 1, false, self.name, true, ".", prompt, true)
    if #card > 0 then
      player.room:doIndicate(player.id, {target.id})
      self.cost_data = {tos = {target.id}, cards = card}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name, player:isMale() and 1 or 2)
    room:notifySkillInvoked(player, self.name, "offensive", {target.id})
    room:throwCard(self.cost_data.cards, self.name, player, player)
    if not target.dead then
      room:useVirtualCard("analeptic", nil, target, target, self.name, true)
    end
    if player ~= target and not target.dead then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
    end
  end,

  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@@efengqi__luanwu_zhendu-round", 0)
  end,
}
jiaxu:addRelatedSkill(efengqi__zhendu)

Fk:loadTranslationTable{
  ["efengqi__jiaxu"] = "贾诩",
  ["#efengqi__jiaxu"] = "",
  ["designer:efengqi__jiaxu"] = "胖即是胖&zzcclll朱苦力",
  ["illustrator:efengqi__jiaxu"] = "biou09",

  ["efengqi__wansha"] = "完杀",
  [":efengqi__wansha"] = "锁定技，你的回合内，除你和处于濒死状态的角色以外的所有角色的【桃】和【无懈可击】均视为【杀】。",
  ["efengqi__weimu"] = "帷幕",
  [":efengqi__weimu"] = "你于回合内伤害时，你可以防止之并摸等量张牌；你于回合外受到伤害时，你可将一张锦囊牌当【闪电】使用，若如此做，防止此伤害。",
  ["#efengqi__weimu-use"] = "帷幕:你可将一张锦囊牌当【闪电】使用，防止你受到的伤害",
  ["#efengqi__weimu-draw"] = "帷幕:你可防止你受到的伤害并摸等量张牌",

  ["efengqi__luanwu"] = "乱武",
  [":efengqi__luanwu"] = "限定技，轮次开始时，你可以令所有角色同时选择两项：1.于本轮获得“鸩毒”；2.翻面；3.摸两张牌。",
  ["efengqi__luanwu_poison"] = "于本轮获得“鸩毒”",
  ["efengqi__luanwu_turnover"] = "翻面",
  ["efengqi__luanwu_draw2"] = "摸两张牌",
  ["#efengqi__luanwu-choice"] = "乱武：请选择执行2项效果",
  ["@@efengqi__luanwu_zhendu-round"] = "鸩毒",

  ["efengqi__zhendu"] = "鸩毒",
  [":efengqi__zhendu"] = "一名角色的出牌阶段开始时，你可以弃置一张手牌。若如此做，该角色视为使用一张【酒】，然后若该角色不为你，你对其造成1点伤害。",
  ["#efengqi__zhendu-invoke"] = "鸩毒：你可以弃置一张手牌视为 %dest 使用一张【酒】，然后你对其造成1点伤害",
  ["#efengqi__zhendu-self"] = "鸩毒：你可以弃置一张手牌视为使用一张【酒】",

  ["$efengqi__wansha1"] = "神仙难救，神仙难救啊。",
  ["$efengqi__wansha2"] = "我要你三更死，谁敢留你到五更！",
  ["$efengqi__weimu1"] = "此计伤不到我。",
  ["$efengqi__weimu2"] = "你奈我何？",
  ["$efengqi__luanwu1"] = "哼哼哼……坐山观虎斗！",
  ["$efengqi__luanwu2"] = "哭喊吧，哀求吧，挣扎吧，然后，死吧！",
  ["$efengqi__zhendu1"] = "斩草务尽，以绝后患。", -- 男配音
  ["$efengqi__zhendu2"] = "这皇宫，只能有一位储君。", -- 女配音
  ["~efengqi__jiaxu"] = "我的时辰……也到了……",
}

local lusu = General(extension, "efengqi__lusu", "wu", 3)
Fk:loadTranslationTable{
  ["efengqi__lusu"] = "鲁肃",
  ["#efengqi__lusu"] = "独断的外交家",
  ["cv:efengqi__lusu"] = "",
  ["designer:efengqi__lusu"] = "低调的温柔",
  ["illustrator:efengqi__lusu"] = "黯荧岛",
  ["~efengqi__lusu"] = "此联盟已破，吴蜀休矣……",
}
local haoshi = fk.CreateActiveSkill{
  name = "efengqi__haoshi",
  anim_type = "drawcard",
  card_num = 0,
  target_num = 0,
  prompt = "#efengqi__haoshi",
  card_filter = Util.FalseFunc,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local nums = {0,1,2,3,4,5}
    for _, p in ipairs(room.alive_players) do
      table.removeOne(nums, p:getHandcardNum())
    end
    if #nums == 0 then nums = {0} end
    local num = table.random(nums)
    player:drawCards(num, self.name)
    if player.dead or player:isKongcheng() then return end
    num = (player:getHandcardNum() + 1) // 2
    local targets = table.map(room:getOtherPlayers(player, false), Util.IdMapper)
    if #targets == 0 then return end
    local tos, ids = room:askForChooseCardsAndPlayers(player, num, num, targets, 1, 1, ".|.|.|hand", "#efengqi__haoshi-give:::"..num,
    self.name, false)
    room:obtainCard(tos[1], ids, false, fk.ReasonGive, player.id, self.name)
  end,
}
lusu:addSkill(haoshi)

Fk:loadTranslationTable{
  ["efengqi__haoshi"] = "好施",
  [":efengqi__haoshi"] = "出牌阶段限一次，你可以摸随机0~5张牌（场上已有的手牌数不会被随机到），再将一半手牌（向上取整）交给一名其他角色。",
  ["#efengqi__haoshi"] = "好施：摸随机0-5张牌（不被随机到已有的手牌数），再将一半手牌交给一名其他角色",
  ["#efengqi__haoshi-give"] = "好施：将 %arg 张手牌交给一名其他角色",
  ["$efengqi__haoshi1"] = "拿去拿去，莫跟哥哥客气！",
  ["$efengqi__haoshi2"] = "来来来，见面分一半。",
}

local dimeng = fk.CreateTriggerSkill{
  name = "efengqi__dimeng",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart, fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.Damaged then return true end
      return player.phase == Player.Finish
    end
  end,
  on_cost = function (self, event, target, player, data)
    local _, dat = player.room:askForUseActiveSkill(player, "efengqi__dimeng_active", "#efengqi__dimeng-choose", true)
    if dat then
      player.room:sortPlayersByAction(dat.targets)
      self.cost_data = {tos = dat.targets}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(table.map(self.cost_data.tos, Util.Id2PlayerMapper)) do
      if not p.dead then
        p:drawCards(1, self.name)
      end
    end
    while not player.dead do
      local _, dat = player.room:askForUseActiveSkill(player, "efengqi__dimeng_active", "#efengqi__dimeng-choose", true)
      if not dat then break end
      local tos = dat.targets
      room:sortPlayersByAction(tos)
      room:doIndicate(player.id, tos)
      player:broadcastSkillInvoke(self.name)
      for _, p in ipairs(table.map(tos, Util.Id2PlayerMapper)) do
        if not p.dead then
          p:drawCards(1, self.name)
        end
      end
    end
  end,
}
lusu:addSkill(dimeng)
local dimeng_active = fk.CreateActiveSkill{
  name = "efengqi__dimeng_active",
  card_num = 0,
  target_num = 2,
  card_filter = Util.FalseFunc,
  target_tip = function (self, to_select, selected, selected_cards, card, selectable, extra_data)
    if #selected == 0 and selectable then
      local to = Fk:currentRoom():getPlayerById(to_select)
      local num = 6 - to:getHandcardNum()
      if table.find(Fk:currentRoom().alive_players, function (p)
        return p ~= to and p:getHandcardNum() == num
      end) then
        return "@efengqi__dimeng:::"..num
      end
    end
  end,
  target_filter = function(self, to_select, selected)
    local to = Fk:currentRoom():getPlayerById(to_select)
    if to:getHandcardNum() > 6 then return false end
    if #selected < 2 then
      if #selected == 0 then return true end
      local first = Fk:currentRoom():getPlayerById(selected[1])
      return to:getHandcardNum() + first:getHandcardNum() == 6
    end
  end,
}
Fk:addSkill(dimeng_active)

Fk:loadTranslationTable{
  ["efengqi__dimeng"] = "缔盟",
  [":efengqi__dimeng"] = "结束阶段，或当你受到伤害后，你可以令两名手牌数之和为6的角色各摸一张牌，然后你可以重复此流程。",
  ["efengqi__dimeng_active"] = "缔盟选人",
  ["#efengqi__dimeng-choose"] = "缔盟：你可以令两名手牌数之和为6的角色各摸一张牌",
  ["@efengqi__dimeng"] = "缺%arg",
  ["$efengqi__dimeng1"] = "以和为贵，以和为贵。",
  ["$efengqi__dimeng2"] = "合纵连横，方能以弱胜强。",
}

local sunjian = General:new(extension, "efengqi__sunjian", "wu", 4, 5)

local yinghun = fk.CreateTriggerSkill{
  name = "efengqi__yinghun",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start and player:isWounded()
  end,
  on_cost = function (self, event, target, player, data)
    local success, dat = player.room:askForUseActiveSkill(player, "efengqi__yinghun_active",
    "#efengqi__yinghun-ask:::"..player:getLostHp(), true)
    if success and dat then
      self.cost_data = dat
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data.targets[1])
    local n = player:getLostHp()
    if self.cost_data.interaction == "efengqi__yinghun_draw" then
      to:drawCards(n, self.name)
    else
      local cards = room:askForCardsChosen(player, to, 1, n, "he", self.name, "#efengqi__yinghun-throw::"..to.id..":"..n)
      room:throwCard(cards, self.name, to, player)
      n = n - #cards
      if n > 0 then
        local tos = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper),
        1, 1, "#efengqi__yinghun-draw:::"..n, self.name, false)
        to = room:getPlayerById(tos[1])
        to:drawCards(n, self.name)
      end
    end
  end,
}
sunjian:addSkill(yinghun)
local yinghun_active = fk.CreateActiveSkill{
  name = "efengqi__yinghun_active",
  card_num = 0,
  target_num = 1,
  interaction = function(self)
    return UI.ComboBox { choices = {"efengqi__yinghun_throw", "efengqi__yinghun_draw"} }
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    local to = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and (self.interaction.data == "efengqi__yinghun_draw" or not to:isNude())
  end,
}
Fk:addSkill(yinghun_active)

local polu = fk.CreateTriggerSkill{
  name = "efengqi__polu",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.DamageCaused},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.to:getHandcardNum() <= player:getMark("@efengqi__polu")
  end,
  on_use = function (self, event, target, player, data)
    data.damage = data.damage + 1
  end,
  on_acquire = function (self, player, is_start)
    local n = #player.room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e)
      local use = e.data[1]
      return use.card.name == "guding_blade"
    end, Player.HistoryGame)
    player.room:setPlayerMark(player, "@efengqi__polu", n)
  end,
  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@efengqi__polu", 0)
  end,
  refresh_events = {fk.CardUsing},
  can_refresh = function (self, event, target, player, data)
    return data.card.name == "guding_blade" and player:hasSkill(self, true)
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:addPlayerMark(player, "@efengqi__polu")
  end,
}
sunjian:addSkill(polu)

local wulie = fk.CreateTriggerSkill{
  name = "efengqi__wulie$",
  events = {fk.Deathed},
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and ((data.damage and data.damage.from and data.damage.from.kingdom == "wu") or target.kingdom == "wu")
  end,
  on_trigger = function(self, event, target, player, data)
    self.cancel_cost = false
    if target.kingdom == "wu" then
      self:doCost(event, target, player, data)
    end
    if self.cancel_cost then return false end
    if data.damage and data.damage.from and data.damage.from.kingdom == "wu" then
      self:doCost(event, target, player, data)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local targets = player.room:askForChoosePlayers(player, table.map(player.room.alive_players, Util.IdMapper),
    1, 99, "#efengqi__wulie-choose:::" .. player:usedSkillTimes(self.name, Player.HistoryGame) + 1, self.name, true)
    if #targets > 0 then
      self.cost_data = targets
      return true
    end
    self.cancel_cost = true
  end,
  on_use = function(self, event, target, player, data)
    local targets = self.cost_data
    local room = player.room
    room:sortPlayersByAction(targets)
    room:addPlayerMark(player, "@os_ex__polu")
    for _, pid in ipairs(targets) do
      local p = room:getPlayerById(pid)
      if not p.dead then
        p:drawCards(player:usedSkillTimes(self.name, Player.HistoryGame))
      end
    end
  end,
}
sunjian:addSkill(wulie)

Fk:loadTranslationTable{
  ["efengqi__sunjian"] = "孙坚",
  ["#efengqi__sunjian"] = "武烈帝",
  ["illustrator:efengqi__sunjian"] = "LiuHeng",
  ["designer:efengqi__sunjian"] = "yyuaN",

  ["efengqi__yinghun"] = "英魂",
  [":efengqi__yinghun"] = "准备阶段，你可以弃置一名角色任意张牌，再令一名角色摸任意张牌 （数量之和为你已损失体力值）。",
  ["#efengqi__yinghun-ask"] = "英魂：弃置一名角色若干张牌，令一名角色摸若干张牌，数量之和为:【 %arg 】",
  ["efengqi__yinghun_draw"] = "仅摸牌",
  ["efengqi__yinghun_throw"] = "先弃后摸",
  ["#efengqi__yinghun-draw"] = "英魂：令一名角色摸 %arg 张牌",
  ["efengqi__yinghun_active"] = "英魂",
  ["#efengqi__yinghun-throw"] = "英魂：弃置 %dest 至多 %arg 张牌",

  ["efengqi__polu"] = "破虏",
  [":efengqi__polu"] = "锁定技，你对手牌数不大于X的角色造成伤害+1 （X为【古锭刀】被使用次数）。",
  ["@efengqi__polu"] = "破虏",

  ["efengqi__wulie"] = "武烈",
  [":efengqi__wulie"] = "主公技，当吴势力角色杀死一名角色或死亡后，你可令任意名角色各摸X张牌（X为你发动过此技能的次数）。",
  ["@efengqi__wulie"] = "武烈",
  ["#efengqi__wulie-choose"] = "武烈：你可选择任意名角色，令这些角色各摸 %arg 张牌",

  ["$efengqi__yinghun1"] = "以吾魂魄，保佑吾儿之基业。",
  ["$efengqi__yinghun2"] = "不诛此贼三族，则吾死不瞑目！",
  ["$efengqi__polu1"] = "匹夫犯我，吾必斩之。",
  ["$efengqi__polu2"] = "鼠辈，这一刀下去定让你看不到明天的太阳。",
  ["$efengqi__wulie1"] = "义定四野，武匡海内。",
  ["$efengqi__wulie2"] = "江东男儿，皆胸怀匡扶天下之志。",
  ["~efengqi__sunjian"] = "江东子弟们，我先走一步了……",
}

local godcaocao = General(extension, "efengqi__godcaocao", "god", 3)
local guixin = fk.CreateTriggerSkill{
  name = "efengqi__guixin",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_cost = function(self, event, target, player, data)
    local choice = player.room:askForChoice(player, {"efengqi__guixin1", "efengqi__guixin2", "Cancel"}, self.name)
    if choice ~= "Cancel" then
      self.cost_data = {choice = choice}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room:getAlivePlayers(), function (p)
      return p:inMyAttackRange(player)
    end)
    if self.cost_data.choice == "efengqi__guixin2" then
      player:turnOver()
      if player.dead then return end
      targets = table.filter(room:getAlivePlayers(), function (p)
        return not p:inMyAttackRange(player)
      end)
    end
    room:doIndicate(player.id, table.map(targets, Util.IdMapper))
    for _, p in ipairs(targets) do
      if player.dead then return end
      if p == player then
        if #player:getCardIds("e") > 0 then
          local id = room:askForCardChosen(player, player, "e", self.name)
          room:obtainCard(player, id, true, fk.ReasonPrey)
        end
      elseif not p:isAllNude() then
        local id = room:askForCardChosen(player, p, "he", self.name)
        room:obtainCard(player, id, false, fk.ReasonPrey)
      end
    end
  end,
}
local feiying = fk.CreateDistanceSkill{
  name = "efengqi__feiying",
  correct_func = function(self, from, to)
    if to:hasSkill(self) then
      return #table.filter(to:getCardIds("h"), function (id)
        return Fk:getCardById(id).suit == Card.Spade
      end)
    end
  end,
}
godcaocao:addSkill(guixin)
godcaocao:addSkill(feiying)
Fk:loadTranslationTable{
  ["efengqi__godcaocao"] = "神曹操",
  ["#efengqi__godcaocao"] = "",
  ["designer:efengqi__godcaocao"] = "zzcclll朱苦力",
  ["illustrator:efengqi__godcaocao"] = "魔奇士",

  ["efengqi__guixin"] = "归心",
  [":efengqi__guixin"] = "你受到伤害后，可以获得攻击范围内有你的角色各一张牌。你可以先翻面，改为没有你。",
  ["efengqi__feiying"] = "飞影",
  [":efengqi__feiying"] = "锁定技，其他角色计算到你的距离+X。（X为你手牌中的♠数）",
  ["efengqi__guixin1"] = "归心：获得攻击范围内有你的角色各一张牌",
  ["efengqi__guixin2"] = "归心：翻面，获得攻击范围内没有你的角色各一张牌",

  ["$efengqi__guixin1"] = "周公吐哺，天下归心！",
  ["$efengqi__guixin2"] = "山不厌高，海不厌深！",
  ["~efengqi__godcaocao"] = "腾蛇乘雾，终为土灰。",
}

local efengqi__godlvbu = General:new(extension, "efengqi__godlvbu", "god", 5,5)
Fk:loadTranslationTable{
  ["efengqi__godlvbu"] = "神吕布",
  ["#efengqi__godlvbu"] = "六臂修罗",
  ["designer:efengqi__godlvbu"] = "汤圆",
  ["cv:efengqi__godlvbu"] = "官方",
  ["illustrator:efengqi__godlvbu"] = "魔奇士",
}
local getAllCardNames = function(guhuo_type, true_name)
  local all_names = {}
  local basics = {}
  local normalTricks = {}
  local delayedTricks = {}
  local equips = {}
  for _, card in ipairs(Fk.cards) do
    if not table.contains(Fk:currentRoom().disabled_packs, card.package.name) and not card.is_derived then
      if card.type == Card.TypeBasic then
        table.insertIfNeed(basics, true_name and card.trueName or card.name)
      elseif card.type == Card.TypeTrick and card.sub_type ~= Card.SubtypeDelayedTrick then
        table.insertIfNeed(normalTricks, true_name and card.trueName or card.name)
      elseif card.type == Card.TypeTrick and card.sub_type == Card.SubtypeDelayedTrick then
        table.insertIfNeed(delayedTricks, true_name and card.trueName or card.name)
      elseif card.type == Card.TypeEquip then
        table.insertIfNeed(equips, true_name and card.trueName or card.name)
      end
    end
  end
  if guhuo_type:find("b") then
    table.insertTable(all_names, basics)
  end
  if guhuo_type:find("t") then
    table.insertTable(all_names, normalTricks)
  end
  if guhuo_type:find("d") then
    table.insertTable(all_names, delayedTricks)
  end
  if guhuo_type:find("e") then
    table.insertTable(all_names, equips)
  end
  return all_names
end
local halberd = {{"py_halberd", Card.Diamond, 12}}
local xiuluo = fk.CreateTriggerSkill{
  events = {fk.EventPhaseStart,fk.Damage,fk.Damaged},
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  name ="efengqi__xiuluo",
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) and target == player then
      if event == fk.EventPhaseStart then
        local banner = player.room:getBanner("@$OutGameWeapons")or {}
        if not table.find(player:getCardIds('e'),function(cid) 
        return Fk:getCardById(cid).name=="py_halberd" end
      ) then
        return target.phase == Player.Start and #player:getAvailableEquipSlots(Card.SubtypeWeapon)>0
      end
      else
        local banner = player.room:getBanner("@$OutGameWeapons")or {}
        return #banner>0 and #player:getAvailableEquipSlots(Card.SubtypeWeapon)>0
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local banner = player.room:getBanner("@$OutGameWeapons")or {}
    if event == fk.EventPhaseStart then
      if not table.find(banner,function(cid) 
        local c = Fk:getCardById(cid)
        return c.name == "py_halberd"
      end
      ) then
        local cid = U.prepareDeriveCards(room, {{"py_halberd", Card.Diamond, 12}}, "efengqi__xiuluo_py_halberd")[1]
        if U.canMoveCardIntoEquip(player, cid, true) then
          --room:setCardMark(Fk:getCardById(cid), MarkEnum.DestructOutEquip, 1)
        room:moveCardIntoEquip(player, cid, self.name, true, player)
        end
      else
        local cid = table.filter(banner,function(cid) 
          local c = Fk:getCardById(cid)
          return c.name == "py_halberd"
        end
        )[1]
        if U.canMoveCardIntoEquip(player, cid, true) then
          --table.removeOne(banner,cid)
          --room:setBanner("@$OutGameWeapons", banner)
          room:setCardMark(Fk:getCardById(cid), MarkEnum.DestructOutEquip, 1)
          room:moveCardIntoEquip(player, cid, self.name, true, player)
          end
      end

    else
      local cids = table.filter(banner,function(cid) 
        return U.canMoveCardIntoEquip(player, cid, true)
      end
      )
      if #cids>0 then
        local cid = table.random(cids,1)[1]
        if cid then
          --table.removeOne(banner,cid)
          --room:setBanner("@$OutGameWeapons", banner)
          room:setCardMark(Fk:getCardById(cid), MarkEnum.DestructOutEquip, 1)
          room:moveCardIntoEquip(player, cid, self.name, true, player)
        end
      end
    end
  end,
  on_acquire = function (self, player, is_start)
    local room = player.room
    local x = player:getMark("xiuluo__extraslot")
    if x<5 then
      while x < 5 do
        x=x+1
        room:addPlayerEquipSlots(player, { Player.WeaponSlot })
        if x == 5 then
          break
        end
      end
    room:setPlayerMark(player,"xiuluo__extraslot",x)
    end
    local banner= room:getBanner("@$OutGameWeapons") or {}
    local ingame = getAllCardNames("e")
    local banned = {"kingsbane","poisonous_dagger"}
    for _, card in ipairs(Fk.cards) do
      local name = card.name
      if card and card.type == Card.TypeEquip and card.sub_type == Card.SubtypeWeapon and not table.contains(banned,name) then
        --print(Util.TranslateMapper(name))
      if not table.find(ingame, function (ingamename)
        return ingamename == name
      end) then
        if #table.filter(banner,function(cid)
          local card1=Fk:getCardById(cid)
        return card1.name == card.name and card1.suit == card.suit and card1.number == card.number end
        )==0 then
        local c = room:printCard(name, card.suit, card.number)
        table.insertIfNeed(banner, c.id)
        end
      end
    end
    end
    room:setBanner("@$OutGameWeapons", banner)
  end,
  on_lose = function (self, player, is_death)
    local room = player.room
    local x = player:getMark("xiuluo__extraslot")
    if x~=0 then 
    while x >0 do
      x=x-1
      room:removePlayerEquipSlots(player, { Player.WeaponSlot })
      if x == 0 then
        break
      end
    end
  end
  room:setPlayerMark(player,"xiuluo__extraslot",x)
  end,
  refresh_events = {fk.AfterCardsMove,fk.BeforeCardsMove},
  can_refresh = function (self, event, target, player, data)
    return true
  end,
  on_refresh= function (self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
    for _, move in ipairs(data) do
      if move.toArea == Card.Void then
        for _, info in ipairs(move.moveInfo) do
          local card = Fk:getCardById(info.cardId, true)
          if card and card.type == Card.TypeEquip and card.sub_type == Card.SubtypeWeapon then
            local banner = room:getBanner("@$OutGameWeapons")or {}
            table.insertIfNeed(banner,info.cardId)
          room:setBanner("@$OutGameWeapons", banner)
          end
        end
      end
    end
  else
    for _, move in ipairs(data) do
      if move.toArea and move.toArea ~= Card.Void then
        for _, info in ipairs(move.moveInfo) do
          local banner = room:getBanner("@$OutGameWeapons")or {}
          if table.contains(banner,info.cardId) then
          local card = Fk:getCardById(info.cardId, true)
          if card and card.type == Card.TypeEquip and card.sub_type == Card.SubtypeWeapon then
            table.removeOne(banner,info.cardId)
          room:setBanner("@$OutGameWeapons", banner)
          room:setCardMark(card, MarkEnum.DestructOutEquip, 1)
          end
        end
      end
      end
    end
  end
  end,
}
local shenfen = fk.CreateViewAsSkill{
  name = "efengqi__shenfen",
  anim_type = "offensive",
  pattern = "fire__slash",
  card_filter = function(self, to_select, selected)
    local card = Fk:getCardById(to_select)
    return card and card.type == Card.TypeEquip and card.sub_type == Card.SubtypeWeapon
  end,
  view_as = function(self, cards)
    if #cards < 1 then return nil end
    local c = Fk:cloneCard("fire__slash")
    c.skillName = self.name
    c:setMark(self.name, cards)
    return c
  end,
  before_use = function(self, player, use)
    local room = player.room
    if #use.card:getTableMark(self.name)>0 then
      --local banner= room:getBanner("@$OutGameWeapons") or {}
      --table.insertTableIfNeed(banner,use.card:getTableMark(self.name))
      --room:setBanner("@$OutGameWeapons", banner)
    room:moveCardTo(use.card:getTableMark(self.name), Card.Void, nil, fk.ReasonJustMove, self.name, nil, true, player.id)
    end
  end,
  enabled_at_response = function(self, player, response)
    return not response
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
}
local shenfen_target = fk.CreateTargetModSkill {
  name = "#efengqi__shenfen_target",
  extra_target_func = function(self, player, skill, card)
    if card and table.contains(card.skillNames, "efengqi__shenfen") and #card:getTableMark("efengqi__shenfen")>0 then
            return #card:getTableMark("efengqi__shenfen")-1
    end
    return 0
  end,
}
shenfen:addRelatedSkill(shenfen_target)
efengqi__godlvbu:addSkill(xiuluo)
efengqi__godlvbu:addSkill(shenfen)
Fk:loadTranslationTable{
  ['steam_outofgame'] = "一个额外牌堆，由本局游戏开始时牌堆中不包含的武器牌构成（即在牌盒中剩余的武器牌，以及其他额外牌堆中的武器牌）。<br>①当一张武器牌被销毁或移除后，亦或是移动到虚空（或额外牌堆）后，会回到牌盒中的这个牌堆。<br>②离开这个牌堆的牌，会在进入装备区和处理区以外的区域时被销毁，重新洗回牌盒中的这个牌堆。",

  ["efengqi__xiuluo"]="修罗",
  [":efengqi__xiuluo"]="锁定技，你有五个额外的武器栏。准备阶段，若你未装备着<a href=':py_halberd'>【无双方天戟】</a>，你装备之。你造成或受到伤害后，从<a href='steam_outofgame'>游戏外</a>抽一张武器牌并装备。",
  ["efengqi__shenfen"]="神愤",
  [":efengqi__shenfen"]="出牌阶段限一次，你可以移除任意张武器牌，视为使用一张目标上限相等的火【杀】。",
  ["@$OutGameWeapons"]="游戏外武器牌",
  ["xiuluo__weapon"]="游戏外武器牌",

  ["$efengqi__xiuluo1"]="生我何用，不倒凡力；灭我何用，不减狂傲！",
  ["$efengqi__xiuluo2"]="舍身入魔，佛奈我何？",
  ["$efengqi__xiuluo3"]="修罗之征，岂留活口？",
  ["$efengqi__shenfen1"]="我要神佛烟消云散，我要人间火海滔天！",
  ["$efengqi__shenfen2"]="神罚灭世，炼狱即临！",
  ["~efengqi__godlvbu"] = "神魔之躯，亦难挡刀剑之力……",
}


return extension
